import ajax from './ajax'


const _processDownload = function(res, filename) {
  let link = document.createElement('a');
  let url = window.URL.createObjectURL(res.data);
  link.href = url;
  link.download = filename;
  link.click();
  setTimeout(function(){
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);  
  }, 100);
}

export default {

  removeDuplicate(header, files, onSuccess, onError) {
    
    let fd = new FormData();
    fd.append('header', header);
    fd.append('file1', files[0]);
    fd.append('file2', files[1]);
    ajax.post('/tool/excel/duplicate',fd,{headers:{'Content-Type':'multipart/form-data'},responseType:'blob'})
        .then(res=>{
          onSuccess(res);
          // TODO: do in vue!
          _processDownload(res, '(已标记重复)' + files[0].name);
        })
        .catch(onError?onError:err=>{});
  },

  tagRepeat(header, files, onSuccess, onError) {
    let fd = new FormData();
    fd.append('header', header);
    fd.append('file', files[0]);
    ajax.post('/tool/excel/repeating',fd,{headers:{'Content-Type':'multipart/form-data'},responseType:'blob'})
        .then(res=>{
          onSuccess(res);
          // TODO: do in vue!
          _processDownload(res, '(已标记重复)' + files[0].name);
        })
        .catch(onError?onError:err=>{});
  },

  sendSms(template, channel, phone, onSuccess, onError) {
      ajax.post('/sms/'+template+'/send/' + phone + '?channel=' + channel)
        .then(onSuccess)
        .catch(onError?onError:err=>{});
  }
}